package org.satish.gui;

import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.satish.core.LOCCount;

public class UIMain extends JPanel implements ActionListener {
	
    private JButton openButton;
    private JTextArea log;
    private JTextField textField;
    private JButton calculateButton;
    private JFileChooser fc;
    private JScrollPane logScrollPane;
    private JCheckBox recursiveOption;
    private JCheckBox emptyLinesOption;

    public UIMain() {
        super(new BorderLayout());

        //Create a file chooser
        fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        
        JPanel fileChooserPanel = new JPanel(); //use FlowLayout
        
        //Location label and text field
        textField = new JTextField(20);
        JLabel label = new JLabel("Location");
        
        //Create the browse button.
        openButton = new JButton("Browse");
        openButton.setMnemonic(KeyEvent.VK_B);
        openButton.addActionListener(this);        
        
        fileChooserPanel.add(label);
        fileChooserPanel.add(textField);
        fileChooserPanel.add(openButton);
        
        //Options panel
        JPanel optionsPanel = new JPanel();
        recursiveOption = new JCheckBox("Scan Recursively");
        recursiveOption.setMnemonic(KeyEvent.VK_S);
        recursiveOption.setSelected(true);
        emptyLinesOption = new JCheckBox("Ignore whitespace");
        emptyLinesOption.setMnemonic(KeyEvent.VK_I);
        optionsPanel.add(recursiveOption);
        optionsPanel.add(emptyLinesOption);
        
        //Calculate panel
        JPanel calculatePanel = new JPanel();
        calculateButton = new JButton("Calculate LOC");
        calculateButton.setMnemonic(KeyEvent.VK_C);
        calculateButton.addActionListener(this);
        calculatePanel.add(calculateButton);

        //Create the log area
        log = new JTextArea(5,20);
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
        logScrollPane = new JScrollPane(log);

        //Add the buttons and the log to this panel.
        add(fileChooserPanel, BorderLayout.PAGE_START);
        add(optionsPanel, BorderLayout.BEFORE_LINE_BEGINS);
        add(calculatePanel, BorderLayout.CENTER);
        add(logScrollPane, BorderLayout.PAGE_END);
    }

    public void actionPerformed(ActionEvent e) {

        //Handle open button action.
        if (e.getSource() == openButton) {
            int returnVal = fc.showOpenDialog(UIMain.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                textField.setText(file.getPath());
            }

        //Handle calculate button action.
        } else if (e.getSource() == calculateButton) {
        	log.setText("");
        	LOCCount counter = new LOCCount(textField.getText(),
					recursiveOption.isSelected(), emptyLinesOption.isSelected());
			try {
				counter.process();
				java.util.List messages = counter.getMessages();
				Iterator it = messages.iterator();
				while(it.hasNext()) {
					String msg = (String)it.next(); 
					log.append(msg + "\n");
				}
			} catch (Exception e1) {
				log.append("File or Directory not found");
				e1.printStackTrace();
			}
        }
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    public static void createAndShowGUI() {
    	
//    	String lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
    	String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
		try {
			UIManager.setLookAndFeel(lookAndFeel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
        //Create and set up the window.
        JFrame frame = new JFrame("LOC Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(350, 284);

        //Create and set up the content pane.
        JComponent newContentPane = new UIMain();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        SwingUtilities.updateComponentTreeUI(frame);
        frame.pack();
        frame.setVisible(true);
        frame.setResizable(false);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
